package com.changgou.pay.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.pay.config.RabbitMQConfig;
import com.changgou.pay.service.WxPayService;
import com.changgou.util.ConvertUtils;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wxpay")
public class WxPayController {
    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 下单生成二维码
     * @param orderId
     * @param money
     * @return
     */
    @GetMapping("/nativePay")
    public Result nativePay(@RequestParam("orderId") String orderId, @RequestParam("money") Integer money){
        Map resultMap = wxPayService.nativePay(orderId, money);
        return new Result(true, StatusCode.OK,"",resultMap);
    }

    /**
     * 回调
     * @param request
     * @param response
     */
    @RequestMapping("/notify")
    public void notifyLogic(HttpServletRequest request, HttpServletResponse response){
        System.out.println("支付成功回调...");

        try {
            //输入流转化为xml字符串
            String xml = ConvertUtils.convertToString(request.getInputStream());
            System.out.println(xml);
            //解析
            Map<String, String> map = WXPayUtil.xmlToMap(xml);
            //调取返回结果
            if ("SUCCESS".equals(map.get("result_code"))){
                Map result = wxPayService.queryOrder(map.get("out_trade_no"));
                System.out.println("查询订单返回结果: " + result);
                //查询结果成功消息发送到mq
                if ("SUCCESS".equals(result.get("result_code"))){
                    Map message = new HashMap();
                    message.put("orderId",result.get("out_trade_no"));
                    message.put("transactionId",result.get("transaction_id"));
                    rabbitTemplate.convertAndSend("", RabbitMQConfig.ORDER_PAY, JSON.toJSONString(message));
                    //完成双向通信
                    rabbitTemplate.convertAndSend("paynotify","",result.get("out_trade_no"));
                }else {
                    System.out.println(map.get( "err_code_des" ));//错误信息描述
                }
            }else {
                System.out.println(map.get( "err_code_des" ));//错误信息描述
            }
            //给微信支付一个响应
            response.setContentType("text/html");
            String data = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            response.getWriter().write(data);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 查询微信订单
     * @param orderId
     * @return
     */
    @GetMapping("/query/{orderId}")
    public Result queryOrder(@PathVariable("orderId") String orderId){
        Map map = wxPayService.queryOrder(orderId);
        return new Result(true,StatusCode.OK,"",map);
    }

    /**
     * 关闭微信订单
     * @param orderId
     * @return
     */
    @GetMapping("/close/{orderId}")
    public Result closeOrder(@PathVariable("orderId") String orderId){
        Map map = wxPayService.closeOrder(orderId);
        return new Result(true,StatusCode.OK,"",map);
    }

}
